package com.cloudsail.domain.activity.service.armory;

import com.cloudsail.domain.activity.model.entity.ActivitySkuEntity;
import com.cloudsail.domain.activity.repository.IActivityRepository;
import com.cloudsail.types.common.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author CloudSailNeverSee
 * @create 2024-12-12 12:41
 * @description
 */
@Slf4j
@Service
public class ActivityArmory implements IActivityArmory, IActivityDispatch {

    @Resource
    IActivityRepository repository;

    @Override
    public boolean assembleActivitySkuByActivityId(Long activityId) {
        List<ActivitySkuEntity> activitySkuEntities = repository.queryActivitySkuListByActivityId(activityId);
        for (ActivitySkuEntity activitySkuEntity : activitySkuEntities) {
            cacheActivitySkuStockCount(activitySkuEntity.getSku(), activitySkuEntity.getStockCountSurplus());
            // 预热活动次数【查询时预热到缓存】
            repository.queryRaffleActivityCountByActivityCountId(activitySkuEntity.getActivityCountId());
        }

        // 预热活动【查询时预热到缓存】
        repository.queryRaffleActivityByActivityId(activityId);

        return true;
    }
    @Override
    public boolean assembleActivitySku(Long sku) {
        // 查库存然后装配到缓存
        ActivitySkuEntity skuEntity = repository.queryActivitySku(sku);
        cacheActivitySkuStockCount(sku, skuEntity.getStockCount());
        // 查询活动信息与次数，从而添加到缓存
        repository.queryRaffleActivityByActivityId(skuEntity.getActivityId());
        repository.queryRaffleActivityCountByActivityCountId(skuEntity.getActivityCountId());
        return true;
    }

    private void cacheActivitySkuStockCount(Long sku, Integer stockCount) {
        String cacheKey = Constants.RedisKey.ACTIVITY_SKU_STOCK_COUNT_KEY + sku;
        repository.cacheActivitySkuStockCount(cacheKey, stockCount);
    }

    @Override
    public boolean subtractionActivitySkuStock(Long sku, Date endDateTime) {
        String cacheKey = Constants.RedisKey.ACTIVITY_SKU_STOCK_COUNT_KEY + sku;
        return repository.subtractionActivitySkuStock(sku, cacheKey, endDateTime);
    }
}
